package com.jiyuren.wheelview.dialog;

import java.util.Calendar;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.jiyuren.wheelview.PickViewConst;
import com.jiyuren.wheelview.R;
import com.jiyuren.wheelview.lib.OptionType;
import com.jiyuren.wheelview.listener.OnDialogClickListener;
import com.jiyuren.wheelview.view.WeekCheckView;
import com.jiyuren.wheelview.view.WheelDate;
import com.jiyuren.wheelview.view.WheelHourMin;
import com.jiyuren.wheelview.view.WheelOptions;
import com.jiyuren.wheelview.view.WeekCheckView.MapKeyComparator;
import com.jiyuren.wheelview.view.WeekCheckView.OnWeekCheckListener;

/**
 * com.pickerview.dialog.CommonPickDialog
 * 
 * @author jiyuren <br/>
 *         create at 2015年5月26日 下午5:17:44
 * @param <T>
 * @param <T>
 */
public class CommonPickDialog<T> extends Dialog implements android.view.View.OnClickListener {
  private static final String TAG = "CommonPickDialog";

  WheelOptions wheelOptions;

  private View rootView; // 总的布局
  WheelHourMin wheelHourMin;
  WheelDate wheelDate;
  private Button btnSubmit, btnCancel;
  private String leftText = "取消", rightText = "确定";
  private static final String TAG_SUBMIT = "submit";
  private static final String TAG_CANCEL = "cancel";

  private StringBuilder weekBuilder = new StringBuilder();
  private StringBuilder weekIndexBuilder = new StringBuilder();
  private String weekIndex = "";
  private String weekIndexCopy = "";
  private String week = "";
  private String weekCopy = "";
  private Context context;
  private OptionType type;
  WeekCheckView weekCheckView;
  private LinearLayout llTop;
  private boolean isCancel = true;

  LinearLayout llCon;
  private OnDialogClickListener dialogClickListener;

  public void setOnDialogClickListener(OnDialogClickListener dialogClickListener) {
    this.dialogClickListener = dialogClickListener;
  }

  public CommonPickDialog(Context context) {
    super(context, R.style.dialog);
    init(context);
  }

  public CommonPickDialog(Context context, int theme) {
    super(context, theme);
    init(context);
  }

  public CommonPickDialog(Context context, OptionType type) {
    super(context, R.style.dialog);
    this.type = type;
    init(context);
  }

  public CommonPickDialog(Context context, int theme, OptionType type) {
    super(context, theme);
    this.type = type;
    init(context);

  }

  /**
   * 添加自定义view 到dialog
   * 
   * @param view
   */
  public void addView(View view) {
    if (null != llCon) {
      llCon.addView(view);
    }
  }

  /**
   * 添加标题栏
   * 
   * @param view
   */
  public void addTitleView(View view) {
    if (null != llTop) {
      llTop.addView(view);
    }
  }

  public void setIsCancel(boolean isCancel) {
    this.isCancel = isCancel;
  }

  /**
   * @param context2
   */
  private void init(Context context) {
    this.context = context;
    Log.v(TAG, "init()");
    LayoutInflater mLayoutInflater = LayoutInflater.from(context);

    switch (type) {
      case YM_YM:// 年月
        rootView = mLayoutInflater.inflate(R.layout.dialog_date_date, null);
        View dateView = rootView.findViewById(R.id.include_date_);
        wheelDate = new WheelDate(dateView);
        break;
      case TIME_TIME:
        rootView = mLayoutInflater.inflate(R.layout.dialog_time_time, null);
        weekCheckView = (WeekCheckView) rootView.findViewById(R.id.week_view);
        weekCheckView.setOnWeekCheckListener(myWeekCheckLisnter);
        View timeView = rootView.findViewById(R.id.include_time);
        wheelHourMin = new WheelHourMin(timeView);
        for (int i = 0; i < WeekCheckView.WEEKS.length; i++) {
          weekBuilder.append(WeekCheckView.WEEKS[i]).append("、");
          if (i == 0) {
            weekIndexBuilder.append(WeekCheckView.WEEKS.length + "").append("|");
            continue;
          }
          weekIndexBuilder.append(i + 1).append("|");
        }
        week = "周" + weekBuilder.toString().substring(0, weekBuilder.toString().lastIndexOf("、"));
        weekCopy = week;
        weekIndex = weekIndexBuilder.toString().substring(0, weekIndexBuilder.toString().lastIndexOf("|"));
        weekIndexCopy = weekIndex;
        break;
      case OPTIONS:
      case CUSTOM_OPTIONS:
        rootView = mLayoutInflater.inflate(R.layout.dialog_options_options, null);
        // ----转轮
        final View optionspicker = rootView.findViewById(R.id.include_options);
        wheelOptions = new WheelOptions(optionspicker);
        llTop = (LinearLayout) rootView.findViewById(R.id.ll_top);
        break;
      case CUSTOM:
        rootView = mLayoutInflater.inflate(R.layout.pw_custom_view, null);
        llCon = (LinearLayout) rootView.findViewById(R.id.ll_con);
        break;
      default:
        break;
    }
    
    btnSubmit = (Button) rootView.findViewById(R.id.bt_sure);
    btnSubmit.setBackgroundResource(PickViewConst.BT_CONFIRM_BG);
    btnSubmit.setTextColor(context.getResources().getColorStateList(PickViewConst.BT_CONFIRM_TEXT));
    btnSubmit.setTag(TAG_SUBMIT);
    
    btnCancel = (Button) rootView.findViewById(R.id.bt_cancle);
    btnCancel.setBackgroundResource(PickViewConst.BT_CANCLE_BG);
    btnCancel.setTextColor(context.getResources().getColorStateList(PickViewConst.BT_CANCLE_TEXT));
    
    btnCancel.setTag(TAG_CANCEL);
    
    btnSubmit.setOnClickListener(this);
    btnCancel.setOnClickListener(this);
  }

  /**
   *
   */
  @SuppressLint({ "NewApi", "ResourceAsColor" })
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // -----确定和取消按钮
    Log.v(TAG, "onCreate()");
    setContentView(rootView);
  }

  /**
   * 设置week 选中
   * 
   * @param index
   */
  public void setWeekCheck(int... index) {
    if (null != weekCheckView) {
      weekCheckView.setWeekChecked(index);
    }
  }

  @Override
  public void onClick(View v) {
    String tag = (String) v.getTag();
    if (tag.equals(TAG_CANCEL)) {
      if (isCancel) {
        dismiss();
      } else {
        if (null != dialogClickListener)
          dialogClickListener.onCancel();
      }
    } else if (tag.equals(TAG_SUBMIT)) {
      switch (type) {
        case YM_YM:
          initTime(type);
          break;
        case TIME_TIME:
          initTime(type);
          break;
        case OPTIONS:
        case CUSTOM_OPTIONS:
          initOptions();
          break;
        case CUSTOM:
          dismiss();
          if (null != dialogClickListener)
            dialogClickListener.onConfirm();
          break;
        default:
          break;
      }
      return;
    }
  }

  /**
   * 独立双集合
   * 
   * @param <T>
   * 
   * @param options1Items
   * @param options2Items
   */
  @SuppressWarnings("unchecked")
  public void setPicker(List<T> options1Items, List<T> options2Items) {
    wheelOptions.setPicker(options1Items, options2Items);
  }

  /**
   * 独立三集合
   * 
   * @param <T>
   * 
   * @param options1Items
   * @param options2Items
   * @param options3Items
   */
  @SuppressWarnings("unchecked")
  public void setPicker(List<T> options1Items, List<T> options2Items, List<T> options3Items) {
    wheelOptions.setPicker(options1Items, options2Items, options3Items);
  }

  @SuppressWarnings("unchecked")
  public void setPicker(List<T> optionsItems) {
    wheelOptions.setPicker(optionsItems, null, null);
  }

  @SuppressWarnings("unchecked")
  public void setPicker(List<T> options1Items, List<List<T>> options2Items, boolean linkage) {
    wheelOptions.setPicker(options1Items, options2Items, null, linkage);
  }

  @SuppressWarnings("unchecked")
  public void setPicker(List<T> options1Items, List<List<T>> options2Items, List<List<List<T>>> options3Items,
      boolean linkage) {
    wheelOptions.setPicker(options1Items, options2Items, options3Items, linkage);
  }

  /**
   * 设置选中的item位置
   * 
   * @param option1
   */
  public void setSelectOptions(int option1) {
    wheelOptions.setCurrentItems(option1, 0, 0);
  }

  /**
   * 设置选中的item位置
   * 
   * @param option1
   * @param option2
   */
  public void setSelectOptions(int option1, int option2) {
    wheelOptions.setCurrentItems(option1, option2, 0);
  }

  /**
   * 设置选中的item位置
   * 
   * @param option1
   * @param option2
   * @param option3
   */
  public void setSelectOptions(int option1, int option2, int option3) {
    wheelOptions.setCurrentItems(option1, option2, option3);
  }

  /**
   * 设置选项的单位
   * 
   * @param label1
   * @param label2
   */
  public void setLabels(String label1) {
    wheelOptions.setLabels(label1, null, null);
  }

  /**
   * 设置选项的单位
   * 
   * @param label1
   * @param label2
   */
  public void setLabels(String label1, String label2) {
    wheelOptions.setLabels(label1, label2, null);
  }

  /**
   * 设置选项的单位
   * 
   * @param label1
   * @param label2
   * @param label3
   */
  public void setLabels(String label1, String label2, String label3) {
    wheelOptions.setLabels(label1, label2, label3);
  }

  /**
   * 设置时间范围
   * 
   * @param startHourLs
   * @param startMinLs
   * @param endHourLs
   * @param endMinLs
   */
  public void setRangeTime(final List<String> startHourLs, final List<String> startMinLs, final List<String> endHourLs,
      final List<String> endMinLs) {
    wheelHourMin.setTime2TimePicker(startHourLs, startMinLs, endHourLs, endMinLs);
  }

  /**
   * 设置时间范围
   * 
   * @param startHourLs
   * @param startMinLs
   * @param endHourLs
   * @param endMinLs
   */
  public void setRangeDate(final List<String> startYearLs, final List<String> startMonLs, final List<String> endYearLs,
      final List<String> endMonLs) {
    wheelDate.setTime2TimePicker(startYearLs, startMonLs, endYearLs, endMonLs);
  }

  private OnWeekCheckListener myWeekCheckLisnter = new OnWeekCheckListener() {
    @Override
    public void onWeekCheckListener(Map<Integer, String> map) {
      StringBuilder sbWeek = new StringBuilder();
      StringBuilder sbWeekIndex = new StringBuilder();
      if (!map.isEmpty()) {
        MapKeyComparator comparator = new WeekCheckView(context).new MapKeyComparator();
        Map<Integer, String> resultMap = comparator.sortMapByKey(map);
        for (Map.Entry<Integer, String> entry : resultMap.entrySet()) {
          sbWeek.append(entry.getValue()).append("、");
          if (entry.getKey() == 0) {
            sbWeekIndex.append(WeekCheckView.WEEKS.length + "").append("|");
            continue;
          }
          sbWeekIndex.append(entry.getKey() + "").append("|");
        }
        week = "周" + sbWeek.toString().substring(0, sbWeek.toString().lastIndexOf("、"));
        weekIndex = sbWeekIndex.toString().substring(0, sbWeekIndex.toString().lastIndexOf("|"));
      } else {
        week = weekCopy;
        weekIndex = weekIndexCopy;
      }
    }
  };

  /**
   * 设置是否循环滚动
   * 
   * @param cyclic
   */
  public void setCyclic(boolean cyclic) {
    switch (type) {
      case YM_YM:
        wheelDate.setCyclic(cyclic);
        break;
      case TIME_TIME:
        wheelHourMin.setCyclic(cyclic);
        break;
      case OPTIONS:
      case CUSTOM:
      case CUSTOM_OPTIONS:
        wheelOptions.setCyclic(cyclic);
        break;
      default:
        break;
    }
  }

  public void setVisibleItems(int count) {
    switch (type) {
      case YM_YM:
        break;
      case TIME_TIME:
        break;
      case OPTIONS:
      case CUSTOM:
      case CUSTOM_OPTIONS:
        break;
      default:
        break;
    }
  }

  /**
   * 
   */
  private void initOptions() {
    int[] options = wheelOptions.getCurrentItems();
    if (null != dialogClickListener) {
      dialogClickListener.onOptionsSelect(options[0], options[1], options[2]);
    }
    dismiss();
  }

  /**
   * 
   */
  private void initTime(OptionType type) {
    switch (type) {
      case YM_YM:
        int startYear = Integer.valueOf(wheelDate.getTimeRange()[0]);
        int startMonth = Integer.valueOf(wheelDate.getTimeRange()[1]);
        int endYear = Integer.valueOf(wheelDate.getTimeRange()[2]);
        int endMonTh = Integer.valueOf(wheelDate.getTimeRange()[3]);
        
        Log.v("CommonPickDialog","startYear = "+startYear+" startMonth = "+startMonth+" endYear = "+endYear+" endMonTh = "+endMonTh);
        if (startYear > endYear && endYear != 0) {
          Toast.makeText(context, "开始时间不能大于结束时间", 0).show();
          return;
        }
        if (startYear == endYear) {
          if (startMonth > endMonTh) {
            Toast.makeText(context, "开始时间不能大于结束时间", 0).show();
            return;
          }
          if (startMonth == endMonTh && endMonTh != 0) {
            Toast.makeText(context, "开始时间和结束时间不能相同", 0).show();
            return;
          }
        }
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        if ((startYear == year && startMonth > month) || (endYear == year && endMonTh > month)) {
          Toast.makeText(context, "开始时间或者结束时间不能大于当前时间", 0).show();
          return;
        }
        if (null != dialogClickListener)
          dialogClickListener.onConfirm(wheelDate.getTimeRange());
        break;
      case TIME_TIME:
        int startHour = Integer.valueOf(wheelHourMin.getTimeRange()[0]);
        int startMin = Integer.valueOf(wheelHourMin.getTimeRange()[1]);
        int endHour = Integer.valueOf(wheelHourMin.getTimeRange()[2]);
        int endMin = Integer.valueOf(wheelHourMin.getTimeRange()[3]);

        String time = wheelHourMin.getTimeRange()[0] + ":" + wheelHourMin.getTimeRange()[1] + "-"
            + wheelHourMin.getTimeRange()[2] + ":" + wheelHourMin.getTimeRange()[3];
        if (startHour > endHour) {
          Toast.makeText(context, "开始时间不能大于结束时间", 0).show();
          return;
        }
        if (startHour == endHour) {
          if (startMin > endMin) {
            Toast.makeText(context, "开始时间不能大于结束时间", 0).show();
            return;
          }
          if (startMin == endMin) {
            Toast.makeText(context, "开始时间和结束时间不能相同", 0).show();
            return;
          }
        }
        if (null != dialogClickListener)
          dialogClickListener.onTimeConfirm(week, weekIndex.toString(), time);
        break;
      default:
        break;
    }
    dismiss();
  }

  @Override
  public void show() {
    super.show();
    Log.v(TAG, "show()");
    btnCancel.setText(leftText);
    btnSubmit.setText(rightText);
  }

  public void setLeftText(String text) {
    this.leftText = text;
  }

  public void setRightText(String text) {
    this.rightText = text;
  }

}
